<template>
  <el-dialog :title="title" :visible="addDialog" @close="handleClose">
    <el-form :model="formData" :rules="rules" ref="ruleForm">
      <el-form-item label-width="100px" label="文章标题:" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入文章标题"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="100px" label="文章内容:" prop="articleBody">
        <quill-editor v-model="formData.articleBody"> </quill-editor>
      </el-form-item>
      <el-form-item label-width="100px" label="视频地址:">
        <el-input
          v-model="formData.videoURL"
          placeholder="请输入视频地址"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="end">
        <el-col :span="6">
          <el-button size="small" @click="handleClose">取消</el-button>
          <el-button size="small" type="primary" @click="btnOK">确认</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { detail, update, add } from '@/api/hmmm/articles'

export default {
  name: 'ArticleAdd',
  props: {
    addDialog: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      required: true
    },
    artId: {
      type: [String, Number],
      default: null
    }
  },
  data () {
    return {
      formData: {
        title: '',
        articleBody: '',
        videoURL: null
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    if (this.artId) {
      this.getArtDetail()
    }
  },
  methods: {
    handleClose () {
      this.$emit('update:addDialog', false)
      this.formData = {
        title: '',
        articleBody: '',
        videoURL: null
      }
      this.$emit('update:artId', null)
      this.$refs.ruleForm.resetFields()
    },
    async getArtDetail () {
      const { data: { title, articleBody, videoURL } } = await detail({ id: this.artId })
      this.formData.title = title
      this.formData.articleBody = articleBody
      this.formData.videoURL = videoURL
    },
    async btnOK () {
      try {
        await this.$refs.ruleForm.validate()
        if (this.artId) {
          await update({ ...this.formData, id: this.artId })
          this.$message.success('修改文章成功')
        } else {
          await add(this.formData)
          this.$message.success('新增文章成功')
        }
        this.$emit('refresh')
        this.handleClose()
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped lang='scss'>
</style>
